package main

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
	"net/http"
	"os"

	"golang.org/x/text/encoding/simplifiedchinese"
)

var serverIp string = "127.0.0.4"
var serverPort string = "44444"

func main() {
	fmt.Println("m3u8-download-maker-for-ffmpeg")
	http.HandleFunc("/", IndexHandler)
	http.ListenAndServe(fmt.Sprintf("%s:%s", serverIp, serverPort), nil)
}

type M3u8info struct {
	M3u8  string `json:"m3u8"`
	Title string `json:"title"`
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.RequestURI() == "/favicon.ico" {
		return
	}

	pwd, _ := os.Getwd()
	query := r.URL.Query()
	m3u8Base64 := query.Get("m3u8")
	titleBase64 := query.Get("title")
	m3u8, _ := base64.StdEncoding.DecodeString(m3u8Base64)
	title, _ := base64.StdEncoding.DecodeString(titleBase64)
	m3u8Md5 := md5V(m3u8Base64)

	batContentTemplate := "ffmpeg -i \"%s\" -c copy \"%s.mp4\"\r\n\r\nren \"%s.mp4\" \"%s.mp4\"\r\n\r\npause\r\n\r\n"
	batContent := fmt.Sprintf(batContentTemplate, m3u8, m3u8Md5, m3u8Md5, title)
	// batContent, _ = iconv.ConvertString(batContent, "utf-8", "GBK//IGNORE")
	batContent, _ = simplifiedchinese.GBK.NewEncoder().String(batContent)
	batFileName := fmt.Sprintf("%s/%s.bat", pwd, m3u8Md5)
	fileHandle, _ := os.OpenFile(batFileName, os.O_CREATE, 0666)
	io.WriteString(fileHandle, batContent)
	fileHandle.Close()

	fmt.Printf("Make download: '%s' bat file, done!\n", m3u8Md5)
	fmt.Fprintln(w, "done!")
}

func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

func md5V(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}
